package org.example.deadQueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import org.example.RabbitMqUtils;

import java.sql.SQLOutput;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: springboot3
 * @BelongsPackage: org.example.deadQueue
 * @Author: guodf
 * @CreateTime: 2024-01-31  10:20
 * @Description:
 * @Version: 1.0.0
 */
public class Consumer1 {

    // 普通队列交换机
    public static final String NORMAL_EXCHANGE_NAME = "normal_exchange";
    // 死信队列交换机
    public static final String DEAD_EXCHANGE_NAME = "dead_exchange";
    //普通队列
    public static final String NORMAL_QUEUE_NAME = "normal_queue";
    // 死信队列
    public static final String DEAD_QUEUE_NAME = "dead_queue";

    public static void main(String[] args) throws Exception {
        // 创建连接
        Channel channel = RabbitMqUtils.getChannel();
        // 创建普通交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE_NAME, "direct");
        // 创建死信交换机
        channel.exchangeDeclare(DEAD_EXCHANGE_NAME, "direct");
        // 定义死信的参数信息，并设置死信交换机和死信队列
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME); // 声明死信交换机
        arguments.put("x-dead-letter-routing-key", "lisi"); // 死信路由
//        arguments.put("x-message-ttl", 1000);// TTL超时时间
//        arguments.put("x-max-length", 6); // 死信队列长度
        // 创建普通队列
        channel.queueDeclare(NORMAL_QUEUE_NAME, false, false, false, arguments);
        // 创建死信队列
        channel.queueDeclare(DEAD_QUEUE_NAME, false, false, false, null);
        // 普通交换机绑定队列
        channel.queueBind(NORMAL_QUEUE_NAME, NORMAL_EXCHANGE_NAME, "zhangsan");
        // 死信交换机绑定队列
        channel.queueBind(DEAD_QUEUE_NAME, DEAD_EXCHANGE_NAME, "lisi");
        System.out.println("消费者1准备接受消息---");
        // 消费者1接受消息回调
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            if (message.equals("info0")){
                channel.basicReject(delivery.getEnvelope().getDeliveryTag(), false);
                System.out.println("消费者1拒绝消息");
            }else {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                System.out.println("消费者1确认消息");
            }
        };
        channel.basicConsume(NORMAL_QUEUE_NAME, false, deliverCallback, consumerTag -> {
        });
    }
}